<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2023-12-12 11:14:35
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-02-04 10:11:16
 * @FilePath: /hr_new_vue3/src/views/Management/Home/LeaveManagement/Certificate/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 首页-离职管理-离职工作交接 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title"> </PageHeaderNew>
    </template>
    <main>
      <BaseInfo
        ref="baseInfoRef"
        v-model:data="templateData.data"
        v-if="templateData.data"
      />
      <Design
        ref="designRef"
        v-model:data="templateData.data"
        v-if="templateData.data"
      />

      <section v-if="templateData.data.baseInfo.status === 4">
        <header class="title">退回原因</header>
        <div>
          <a-textarea
            v-model="templateData.data.baseInfo.returnReason"
            :auto-size="{
              minRows: 4
            }"
            disabled
          ></a-textarea>
        </div>
      </section>
      <footer>
        <a-button class="btn" @click="router.back()"> 取消 </a-button>
        <a-button
          class="btn"
          type="outline"
          @click="saveOrSend(1)"
          v-if="
            templateData.data.baseInfo.status <= 2 ||
            templateData.data.baseInfo.status === 4
          "
        >
          确认并保存
        </a-button>
        <a-button
          class="btn"
          type="primary"
          @click="saveOrSend(2)"
          v-if="
            templateData.data.baseInfo.status <= 2 ||
            templateData.data.baseInfo.status === 4
          "
        >
          确认发起
        </a-button>
      </footer>
    </main>
  </ContentCard>
  <ConfirmModal
    v-model:visible="modalVisible"
    :data="templateData.data.baseInfo"
    @save="confirmModalSave"
  />
</template>

<script lang="tsx" setup>
import { GetHumanRosterDetail } from '@/apis/management/human/humanRoster';
import {
  getOrganizationDetailById,
  getPositionDetailById,
  getHumanDetail
} from '@/utils/common';
import {
  SendWorkHandover,
  SaveWorkHandover,
  GetSendWorkHandleDetail,
  DelWorkHandleSub
} from '@/apis/management/human/baseSetting/leaveSetting';
import { cloneDeep } from 'lodash';
import Design from './Template/Design.vue';
import BaseInfo from './Template/BaseInfo.vue';
import ConfirmModal from './ConfirmModal.vue';
import { Message, Modal } from '@arco-design/web-vue';

const title = '工作交接';

const router = useRouter();
const userId = +localStorage.getItem('userId');

let baseInfoRef = ref(); // 基础信息ref
let designRef = ref(); // 编辑ref
const templateData = reactive({
  data: {
    userData: {
      name: '',
      mobile: '',
      departmentName: '',
      positionName: '',
      superiorName: '',
      leaveTime: ''
    },
    baseInfo: {
      userId,
      userName: JSON.parse(localStorage.getItem('userInfo'))?.name || '123',
      name: '',
      templateId: undefined,
      remark: '',
      confirmId: undefined, // 确认人id
      confirmName: undefined, // 确认人名称,
      supervisorId: undefined, // 监督人id
      status: 1 // 工作交接状态
    },
    designData: []
  }
});

let initTemplateData = cloneDeep(templateData.data); // 初始化的数据

let handoverDetail = ref();
const getWorkHandoverData = async () => {
  try {
    const res = await GetSendWorkHandleDetail({
      userId
    });
    templateData.data = res;
    await getHumanData();
    templateData.data.userData = humanInfo.value;
    templateData.data.baseInfo.userName = humanInfo.value.name;
    handoverDetail.value = res;
    console.log('====================================');
    console.log(templateData.data);
    console.log('====================================');
  } catch (error: unknown) {
    console.log(error);
  }
};
getWorkHandoverData();
let humanInfo = ref(); // 人员信息
// 获取人员信息
const getHumanData = async () => {
  try {
    const res = await GetHumanRosterDetail({
      id: userId
      // id: 154
    });
    humanInfo.value = res;
    getOrganizationDetailById(humanInfo.value.companyId).then((res: any) => {
      humanInfo.value.companyName = res.name;
    });
    getOrganizationDetailById(humanInfo.value.departmentId).then(
      (res: any) => (humanInfo.value.departmentName = res.name)
    );
    getPositionDetailById(humanInfo.value.positionId).then(
      (res: any) => (humanInfo.value.positionName = res.name)
    );
    // 获取入职时间
    humanInfo.value.enterTime = getControlValue(
      'CC0D5415792B24BBCAD7DF5AB8A25A0AB'
    );
    // 获取直接上级
    getHumanDetail(getControlValue('CECEBAA743F9B4160B40A5A3E78588712')).then(
      (res: any) => (humanInfo.value.superiorName = res.name)
    );
  } catch (error: unknown) {
    console.log(error);
  }
};

// 获取控件的值
const getControlValue = (code: string) => {
  const temp = humanInfo.value.useTemplate.collectionModel[0].controlModel.find(
    (el: any) => el.ctlCode === code
  );
  return temp?.ctlValue?.ctlValue;
};

const checkValidate = async (validate: any) => {
  if (await validate()) return true;
  else return false;
};

let modalVisible = ref(false); // 判断确认时候的弹出框
let modalType = ref(1); // 1 确认并保存 2 确认发起

const saveOrSend = (type: 1 | 2) => {
  modalVisible.value = true;
  modalType.value = type;
};

const uploadFiles = async (data) => {
  for (let key in designRef.value.uploadRefs) {
    await designRef.value.uploadRefs[key].submit();
    data.ziYuan[key].url = JSON.stringify(
      designRef.value.uploadRefs[key].uploadList.map((ele: any) => {
        return {
          fileName: ele.response.useFileName || ele.response.fileName,
          fileUrl: ele.response.DownloadPath || ele.response.fileUrl,
          id: ele.response.id || ele.response.id
        };
      })
    );
  }
};

// 确认并保存
const save = async () => {
  try {
    let temp = cloneDeep(templateData.data);
    await uploadFiles(temp);
    console.log('====================================');
    console.log(temp);
    console.log(designRef.value.uploadRefs);
    console.log('====================================');
    temp.baseInfo.userId = userId;
    if (temp.baseInfo.id) {
      temp = handleEmptyData(temp);
      delete temp.designData;
      delete temp.userData;
      temp.baseInfo.status = 2;
      await SaveWorkHandover(temp);
      if (designRef.value.delIds.length > 0) {
        await DelWorkHandleSub({
          ids: designRef.value.delIds
        });
      }
    } else {
      temp.designData = handleEmptyData(temp.designData);
      delete temp.designData.baseInfo;
      temp.baseInfo.status = 2;
      const temp2 = {
        baseInfo: temp.baseInfo,
        ...temp.designData
      };
      await SendWorkHandover(temp2);
    }
    Message.success('保存成功！');
    // router.back();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 确认发起
const send = async () => {
  try {
    try {
      // if (await checkValidate(confirmRef.value.validate)) {
      //   Message.error('请先填写必填信息！');
      //   return;
      // }

      let temp = cloneDeep(templateData.data);
      console.log('====================================');
      console.log(temp);
      console.log('====================================');
      temp.baseInfo.userId = userId;
      if (temp.baseInfo.id) {
        temp = handleEmptyData(temp);
        delete temp.designData;
        delete temp.userData;
        temp.baseInfo.status = 3;
        await SaveWorkHandover(temp);
        if (designRef.value.delIds.length > 0) {
          await DelWorkHandleSub({
            ids: designRef.value.delIds
          });
        }
      } else {
        temp.designData = handleEmptyData(temp.designData);
        delete temp.designData.baseInfo;
        temp.baseInfo.status = 3;
        const temp2 = {
          baseInfo: temp.baseInfo,
          ...temp.designData
        };
        await SendWorkHandover(temp2);
      }
      Message.success('发起成功！');

      router.back();
    } catch (error: unknown) {
      console.log(error);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 弹出框自定义事件
const confirmModalSave = async () => {
  if (await checkValidate(designRef.value.validate)) {
    Message.error('请先填写必填信息');
    return;
  }
  if (modalType.value === 1) {
    save();
  } else {
    send();
  }
};

const handleEmptyData = (data: any) => {
  console.log('==============data======================');
  console.log(data);
  console.log('====================================');
  for (let i in data) {
    if (i !== 'baseInfo') {
      if (data[i].length > 0)
        data[i] = data[i].filter((el: any) => el.acceptId !== 0);
    }
  }
  return data;
};
</script>

<style lang="less" scoped>
.title {
  min-height: 30px;
  font-weight: 600;
  font-size: 14px;
  background: #edeffd;
  padding: 5px 0;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  &::before {
    content: '';
    margin: 0 5px;
    display: inline-block;
    width: 3px;
    height: 12px;
    border-left: #409efe solid 1px;
    background-color: #165dff;
  }
  .title-right {
    flex: 1;
    text-align: right;
  }
}
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
    margin-left: 10px;
  }
}
</style>
